import { PointerEvent, App, Text, IUI } from 'leafer-ui'
import { ITool, IToolConfig } from '../types'
import { InnerEditorEvent } from '@leafer-in/editor'
import { isUndefined } from '@/utils/is'
import { ITextEditor } from '../core/ITextEditor'
ITextEditor.registerInnerEditor()
Text.setEditInner('ITextEditor')
const isPointOutsideBox = (
	point: { x: number; y: number },
	boxBounds: { x: number; y: number; width: number; height: number }
): boolean => {
	const { x, y, width, height } = boxBounds

	// 判断点是否在 box 区域外
	return (
		point.x < x || point.x > x + width || point.y < y || point.y > y + height
	)
}
export const TextTool: ITool = ({ app, config, commit, target }) => {
	let text: IUI | null = null
	// app.cursor ="move"
	const addText = (e: PointerEvent) => {
		if (text) return
		if (app.editor.editing) return
		const point = e.getPagePoint()
    //如果开启限制
		if (config.text?.limitBox&&isPointOutsideBox({ x: e.x, y: e.y }, target().getBounds())) {
			return
		}
		text = Text.one(
			{
				text: '',
				// editable: true,
				fill: config.text.color,
				fontSize: config.text.fontSize / (app.data?.fitScale ?? 1),
				editSize: 'size'
			},
			point.x,
			point.y
		)
		target().add(text)
		app.editor.openInnerEditor(text, true)
	}
	app.editor.on(InnerEditorEvent.CLOSE, (e: InnerEditorEvent) => {
		if (!text) return
		if (text?.getAttr('text') === '') {
			app.editor.closeInnerEditor()
			target().remove(text)
		} else {
			commit()
		}
		text = null
	})
	const eventsMap = { [PointerEvent.CLICK]: addText }
	return {
		eventsMap,
		active: () => {},
		deactive: () => {
			app.editor.closeInnerEditor()
			text = null
		}
	}
}
